import requests

from django.contrib.admin.models import LogEntry
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from django.contrib.auth import get_permission_codename

from .models import Post,Category,Tag
from .adminforms import PostAdminForm
from typeidea.custom_site import custom_site
from typeidea.base_admin import BaseOwnerAdmin

PERMISSION_API = "http://permission.sso.com/has_perm?user={}&perm_code={}"

# Register your models here.
class PostInline(admin.TabularInline):
    fields = ('title','desc')
    extra = 1
    model = Post

@admin.register(Category,site=custom_site)
class CategoryAdmin(BaseOwnerAdmin):
    inlines = [PostInline,]
    list_display=('name','status','is_nav','post_count','create_time')
    fields = ('name','status','is_nav')

    def post_count(self,obj):
        return obj.post_set.count()
    post_count.short_description = "文章数量"


@admin.register(Tag,site=custom_site)
class TagAdmin(BaseOwnerAdmin):
    list_display=('name','status','create_time')
    fields = ('name','status')

class CategroyOwnerFilter(admin.SimpleListFilter):
    title = '分类过滤器'
    parameter_name = 'owner_categroy'

    def lookups(self,request,model_admin):
        return Category.objects.filter(owner=request.user).values_list('id','name')

    def queryset(self,request,queryset):
        category_id = self.value()
        if category_id:
            return queryset.filter(category_id=self.value())
        return queryset

@admin.register(Post,site=custom_site)
class PostAdmin(BaseOwnerAdmin):

    # 配置权限
    # def has_add_permission(self,request):
        # opts = self.opts
        # codename = get_permission_codename('add',opts)
        # perm_code = "%s.%s"%(opts.app_label,codename)
        # resp = requests.get(PERMISSION_API.format(request.user.username,perm_code))
        # if resp.status_code == 200:
        #     return True
        # return False

    # 更新desc 到Textarea组件
    form = PostAdminForm
    list_display=('title','category','status',
        'owner','create_time','operator')
    list_display_link = []
    list_filter=[CategroyOwnerFilter]
    # list_filter=['category']
    search_fields = ['title','category__name']
    actions_on_top = True 
    actions_on_bottom= True

    exclude = ('owner',)
    # fields = (
    #     ('category','title'),
    #     'desc',
    #     'status',
    #     'content',
    #     'tag'
    #     )
    fieldsets = (
            ('基础配置',{
                'description':'基础配置描述',
                'fields':(
                    ('title','category'),
                    'status',
                    ),
                }),
            ('内容',{
                'fields':(
                        'desc',
                        'content',
                    ),
                }),
            ('额外信息',{
                'classes':('collapse',),
                'fields':('tag',),
                })
        )

    filter_horizontal=('tag',)

    def operator(self,obj):
        return format_html(
                '<a href="{}">编辑</a>',reverse('cus_admin:blog_post_change',args=(obj.id,))
            )
    operator.short_description='操作'

    # class Media:
    #     css = {
    #         'all':("https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css",)
    #     }
    #     js = (
    #         "https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.slim.min.js",
    #         "https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js",
    #         "https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js",
    #         )

@admin.register(LogEntry)
class LogEntryAdmin(admin.ModelAdmin):
    list_display = ['object_repr','object_id','action_flag','user','change_message']